(function (Vue) {
	const STORAGE_KEY = 'items-vuejs'
	const itemStorage = {
		fetch: function () {
			return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
		},
		save: function (items) {
			localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
		}
	}
	const items = [
		{
			id: 1,
			content: 'wenliankai',
			completed: false //是否完成
		},
		{
			id: 2,
			content: '小芳',
			completed: false //是否完成
		},
		{
			id: 3,
			content: '小明',
			completed: true //是否完成
		}
	];

	Vue.directive('app-focus', {
		inserted(el, binding) {
			el.focus()
		},
		update(el, binding) {
			if (binding.value) {
				el.focus()
			}
		}
	})
	var vm = new Vue({
		el: '#todoapp',
		data: {
			// items,
			items: itemStorage.fetch(),
			currentItem: null,//代表的是点击的那个任务项
			filterStatus: 'all'//接受变化的状态值
		},
		watch: {
			items: {
				deep: true,
				handler: function (newItems, oldItems) {
					itemStorage.save(newItems)
				}
			}
		},
		methods: {
			finishEdit(item, index, event) {
				const content = event.target.value.trim();
				if (!content) {
					this.removeItem(index);
					return;
				}
				item.content = content;
				this.currentItem = null

			},
			cancelEdit() {
				this.currentItem = null
			},
			toEdit(item) {
				this.currentItem = item
			},
			addItem: function (event) {
				//1.获取文本框的内容
				const content = event.target.value.trim();
				if (content) {
					var item = {
						id: new Date().getTime(),
						content,
						completed: false //是否完成
					}

					this.items.push(item);
					//清空input
					event.target.value = ""
				}
			},
			removeItem(index) {
				debugger
				this.items.splice(index, 1)
			},
			removeCompleted() {
				this.items = this.items.filter(item => !item.completed)
			}
		},
		computed: {
			filterItems() {
				switch (this.filterStatus) {
					case 'active':
						return this.items.filter(item => !item.completed)
						break;
					case 'completed':
						return this.items.filter(item => item.completed)
						break;
					default:
						return this.items;
				}
			},
			toggleAll: {
				get: function () {
					return this.remaining === 0;
				},
				set: function (newValue) {
					this.items.forEach(function (item) {
						item.completed = newValue
					});
				}

			},
			remaining: function () {
				const unItems = this.items.filter(function (item) {
					return !item.completed
				})
				return unItems.length;
			}
		}
	})
	//当路由hash值发生变后,会自动调用该函数
	window.onhashchange = function () {
		const hash = window.location.hash.substr(2) || 'all';
		vm.filterStatus = hash;
	}
	window.onhashchange()

})(Vue);
